<template>
    <div>
        <el-button type="primary" @click="addRoleFormVisible = true">添加角色</el-button>
        <el-table :data="tableData" style="width: 100%" border row-key="id" :expand-row-keys="expArr"
            @expand-change="expandchange"><!--此处的id为用户id-->
            <el-table-column type="expand" width="50">
                <template #default="scope">
                    <el-row v-for="item, index in scope.row.children" :key="index"
                        :class="['border-bottom', index === 0 ? 'border-top' : '']" algin="middle">
                        <el-col :span="5">
                            <el-tag closable @close="deletRight(scope.row, item.id)">{{ item.authName }}</el-tag>
                            <caret-right-outlined style="font-size:8px;"></caret-right-outlined>
                        </el-col>
                        <el-col :span="18">
                            <el-row v-for="item2, index2 in item.children" :key="index2"
                                :class="[index2 === 0 ? '' : 'border-top']" align="middle">
                                <el-col :span="6">
                                    <el-tag closable @close="deletRight(scope.row, item2.id)" type="success">{{
                                        item2.authName }}</el-tag>
                                    <caret-right-outlined style="font-size:8px;"></caret-right-outlined>
                                </el-col>
                                <el-col :span="18">
                                    <el-tag closable @close="deletRight(scope.row, item3.id)" type="warning"
                                        v-for="item3, index3 in item2.children" :key="index3">
                                        {{ item3.authName }}
                                    </el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index" label="#" width="50" />
            <el-table-column prop="roleName" label="角色名称" />
            <el-table-column prop="roleDesc" label="角色描述" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" :icon="EditOutlined" @click="roleEdit(scope.row)">编辑</el-button>
                    <el-popconfirm width="220" confirm-button-text="是的" cancel-button-text="不, 谢谢" :icon="InfoFilled"
                        icon-color="#626AEF" title="你确定要删除这条数据吗?" @onConfirm="deleteRole(scope.row)"
                        @confirm="deleteRole(scope.row)">
                        <template #reference>
                            <el-button type="danger" :icon="DeleteOutlined">删除</el-button>
                        </template>
                    </el-popconfirm>
                    <!-- <el-button type="danger" :icon="DeleteOutlined" @click="deleteRole(scope.row)">删除</el-button> -->
                    <el-button type="warning" :icon="SettingOutlined" @click="showRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分配权限对话框 -->
        <el-dialog v-model="dialogVisible" title="分配权限" width="30%" :before-close="handleClose">
            <el-tree ref="rightTree" :data="data" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defaultKeys" :props="defaultProps"></el-tree>
            <!-- node-key 每个树节点用来作为唯一标识的属性 
        default-expand-all 是否全部展开
        default-checked-keys设置默认展开和默认选中的节点 需要注意的是，此时必须设置node-key，其值为节点数据中的一个字段名，该字段在整棵树中是唯一的。
        ref可以拿到树的所有属性和方法
  -->
            <span></span>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="setRight">
                        确认
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 添加用户对话框 -->
        <el-dialog v-model="addRoleFormVisible" title="添加用户">
            <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleFormRef">
                <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="addRoleForm.roleName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitAddRoleForm(addRoleFormRef)">提交</el-button>
                    <el-button @click="resetAddRoleForm(addRoleFormRef)">
                        重置
                    </el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 编辑用户对话框 -->
        <el-dialog v-model="editRoleFormVisible" title="编辑用户">
            <el-form :model="editRoleForm" :rules="addRoleRules" ref="editRoleFormRef">
                <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
                    <el-input v-model="editRoleForm.roleName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc" autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitEditRoleForm(editRoleFormRef)">提交</el-button>
                    <el-button @click="resetAddRoleForm(editRoleFormRef)">
                        重置
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, onBeforeMount, reactive } from 'vue'
import { EditOutlined, DeleteOutlined, SettingOutlined, CaretRightOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
const tableData = ref([])


const getRightsList = async () => {
    const { data: res } = await axios.get(`/roles`)
    tableData.value.splice(0);
    res.data.forEach(ele => tableData.value.push(ele))//获取权限列表
}
const deletRight = async (role, rightId) => {
    ElMessageBox.confirm('此操作将永久删除改权限，是否继续？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(async () => {
            const { data: res } = await axios.delete(`roles/${role.id}/rights/${rightId}`)
            role.children = res.data//重新赋值 重新加载权限
            ElMessage({
                type: 'success',
                message: '删除成功'
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '删除取消'
            })
        })

    // const expArr = ref([])
    // const expandchange = (row, expandedRows) => {

    //     expArr.value = []
    //     expandedRows.forEach(ele => expArr.value.push(ele.id));
    // }
}
const defaultProps = { children: 'children', label: 'authName' }
const data = ref([])
const dialogVisible = ref(false)
const defaultKeys = ref([])
const currentRole = ref(null)
const showRightDialog = async (role) => {
    currentRole.value = role;
    dialogVisible.value = true;
    const { data: res } = await axios.get(`rights/tree`)
    data.value = res.data;
    getdefalutkeys(role, defaultKeys.value)
}
const rightTree = ref();
const setRight = async () => {
    dialogVisible.value = false;
    let rids = [...rightTree.value.getCheckedKeys(), ...rightTree.value.getHalfCheckedKeys()].join(',')
    const { data: res } = await axios.post(`roles/${currentRole.value.id}/rights`, { rids: rids })
    if (res.meta.status != 200)
        return ElMessage.error('权限分配失败');
    getRightsList();
    defaultKeys.value = [];
    ElMessage.success('分配权限成功')
}
const getdefalutkeys = (node, arr) => {
    if (!node.children) return arr.push(node.id)
    node.children.forEach(val => { getdefalutkeys(val, arr);  })

}
/* 添加角色 */
const addRoleFormVisible = ref(false)
const addRoleForm = ref({
    roleName: "",
    roleDesc: "",
})
const addRoleRules = reactive({
    roleName: [{
        required: true, message: '请输入角色名称',
    }],
    roleDesc: [{
        required: true, message: '请输入角色描述',
    }]
})
const addRoleFormRef = ref(null)
const submitAddRoleForm = async (formEL) => {
    if (!formEL) return;
    await formEL.validate(async (valid, fields) => {
        if (valid) {
            const { data: res } = await axios.post('/roles', {
                roleName: addRoleForm.value.roleName,
                roleDesc: addRoleForm.value.roleDesc
            })
            getRightsList()
            addRoleFormVisible.value = false
            ElMessage.success("添加成功")
        } else {
            console.log("error submit!", fields);
        }
    })
}
const resetAddRoleForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields()
}
/* 编辑角色 */

const editRoleFormVisible = ref(false)
const editRoleForm = ref({
    id: 0,
    roleName: "",
    roleDesc: "",
})
const roleEdit = (role) => {
    editRoleFormVisible.value = true
    editRoleForm.value.id = role.id
    editRoleForm.value.roleName = role.roleName
    editRoleForm.value.roleDesc = role.roleDesc
}
const editRoleFormRef = ref(null)
const submitEditRoleForm = async (formEL) => {
    if (!formEL) return;
    await formEL.validate(async (valid, fields) => {
        if (valid) {
            const { data: res } = await axios.put(`/roles/${editRoleForm.value.id}`, {
                roleName: editRoleForm.value.roleName,
                roleDesc: editRoleForm.value.roleDesc
            })
            getRightsList()
            editRoleFormVisible.value = false
            ElMessage.success("添加成功")
        } else {
            console.log("error submit!", fields);
        }
    })
}
/* 删除角色 */
const deleteRole = async (role) => {
    const {data:res} =await axios.delete(`/roles/${role.id}`)
    getRightsList()
}
/* 挂载前的操作 */
onBeforeMount(async () => {
    getRightsList();
})
</script>
<style scoped>
.el-table {
    margin: 10px auto;
}
</style>